package com.globefrog.example.consumer.util;

import com.alibaba.druid.pool.DruidDataSource;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.defaults.DefaultSqlSessionFactory;

/**
 * @author : Globe-Frog
 * @date : Create in 2021/7/12
 */
public class DbUtil {

  public static SqlSessionFactorySettingBuilder sqlSessionFactorySettingBuilder() {
    return new SqlSessionFactorySettingBuilder();
  }

  public static DruidDataSource init(String url,
      String username, String password, String driverClassName, Integer initialSize,
      Integer minIdle, Integer maxActive, Integer maxWait) throws SQLException {
    DruidDataSource dataSource = new DruidDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setInitialSize(initialSize);
    dataSource.setMinIdle(minIdle);
    dataSource.setMaxActive(maxActive);
    dataSource.setMaxWait(maxWait);
    dataSource.setMinEvictableIdleTimeMillis(120000);
    dataSource.setValidationQuery("select 'x'");
    dataSource.setTestWhileIdle(true);
    dataSource.setTestOnBorrow(false);
    dataSource.setTestOnReturn(false);
    dataSource.setValidationQueryTimeout(1); // 检测连接是否有效超时时间
    dataSource.setPoolPreparedStatements(false); // ali建议mysql下关闭
    dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
    String filters = "log4j,config";
    dataSource.setFilters(filters);
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(1800);
    dataSource.setLogAbandoned(true);
    dataSource.setConnectionProperties("config.decrypt=false");
    dataSource.setKeepAlive(true);
    dataSource.setBreakAfterAcquireFailure(false);
    Properties connectProperties = new Properties();
    connectProperties.setProperty("druid.stat.slowSqlMillis", "5000");
    connectProperties.setProperty("druid.stat.logSlowSql", "true");
    connectProperties.setProperty("druid.log.rs", "false");
    dataSource.setConnectProperties(connectProperties);
    return dataSource;
  }

  public static class SqlSessionFactorySettingBuilder extends SqlSessionFactoryBuilder {

    @Override
    public SqlSessionFactory build(Configuration config) {
      config.setLazyLoadingEnabled(false);
      config.setCacheEnabled(false);
      config.setLocalCacheScope(LocalCacheScope.STATEMENT);
      config.setCallSettersOnNulls(true);
      config.setMapUnderscoreToCamelCase(true);
      return new DefaultSqlSessionFactory(config);
    }
  }
}
